package com.base.unionFindSets;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName LongestConsecutive
 * @Description 128. 最长连续序列
 * 给定一个未排序的整数数组 nums ，找出数字连续的最长序列（不要求序列元素在原数组中连续）的长度。
 * <p>
 * 请你设计并实现时间复杂度为O(n) 的算法解决此问题。
 * <p>
 * <p>
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/longest-consecutive-sequence
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * @Author li
 * Date 2021/9/7 21:17
 * Copyright
 **/
public class LongestConsecutive {
    /**
     * 超出时间限制
     * @param nums
     * @return
     */
    public int longestConsecutive(int[] nums) {
        if (nums.length==0){
            return 0;
        }

        Arrays.sort(nums);
        int longestLength = 1;
        for (int i =0;i< nums.length-1;i++) {
            int curLength = 1;
            if (nums[i] + 1 == nums[i + 1]){
                curLength++;
                i++;
                while (nums[i] + 1 == nums[i + 1]||nums[i] == nums[i + 1]){
                    if (nums[i]+1==nums[i+1]){
                        curLength++;
                    }
                    i++;
                }
            }
            i++;
            longestLength = Math.max(curLength,longestLength);
        }
        return longestLength;


    }

    /**
     * 先排序，然后在一次遍历
     * @param nums
     * @return
     */
    public int longestConsecutive2(int[] nums) {
        if (nums.length==0){
            return 0;
        }

        Arrays.sort(nums);
        int longestLength = 1;
        for (int i =0;i< nums.length-1;i++) {
            int curLength = 1;
            if (nums[i] + 1 == nums[i + 1]||nums[i] == nums[i + 1]){
                if (nums[i]+1==nums[i+1]){
                    curLength++;
                }
                i++;
                while (i+1<nums.length&&(nums[i] + 1 == nums[i + 1]||nums[i] == nums[i + 1])){
                    if (nums[i]+1==nums[i+1]){
                        curLength++;
                    }
                    i++;
                }
            }
            longestLength = Math.max(curLength,longestLength);
        }
        return longestLength;
    }
}
